void print_dir(MINODE* dir)
{
	int i, j;
	char buf[MAX_BLOCK_SIZE], *pnt, curDirEnt[EXT2_MAX_FILE_LENGTH];
	EXT2_DISK* diskInfo;
	MINODE* curInode;
	
	if (dir->mounted)
	{
		get_device_info(dir->mountedDevice->handle, &diskInfo);
		dir = get_inode(dir->mountedDevice->handle, ROOT_INODE);
	}
	else
		get_device_info(dir->location.deviceHandle, &diskInfo);
		
	for (i = 0; i < NUM_DIRECT_BLOCKS; i++)
	{
		if (dir->inode.i_block[i] != 0)
		{
			if (read_blk(dir->location.deviceHandle, dir->inode.i_block[i], diskInfo->blockSize, buf) == -1)
				return;

			pnt = buf; j = 0;
			while (j < diskInfo->blockSize)
			{
				memset(curDirEnt, '\0', EXT2_MAX_FILE_LENGTH);
				strncpy(curDirEnt, ((DIR*)pnt)->name, ((DIR*)pnt)->name_len);
				curDirEnt[((DIR*)pnt)->name_len] = '\0';
				curInode = get_inode(dir->location.deviceHandle, ((DIR*)pnt)->inode);
				print_inode_mode(curInode->inode.i_mode);
				printf("%3d %4d %4d %10d %.15s %s\n", curInode->inode.i_links_count, curInode->inode.i_uid,
					curInode->inode.i_gid, curInode->inode.i_size, ctime((time_t*)&(curInode->inode.i_mtime)) + 4, curDirEnt);
				put_inode(curInode);
				j += ((DIR*)pnt)->rec_len; pnt += ((DIR*)pnt)->rec_len;
			}
		}
	}
	if (dir->mounted)
		put_inode(dir);
}

void print_file(MINODE* mip, char* name)
{
	print_inode_mode(mip->inode.i_mode);
	printf("%3d %4d %4d %8d %.15s %s\n", mip->inode.i_links_count, mip->inode.i_uid,
		mip->inode.i_gid, mip->inode.i_size, ctime((time_t*)&(mip->inode.i_mtime)) + 4, name);
}

int do_ls(char* pathName)
{	
	char fullPath[MAX_PATH_LENGTH];
	MINODE* mip;
	LOC iLoc;
		
	printf("\n******************** JRR ls program ********************\n");
	
	/* CWD */
	if (strlen(pathName) == 0)
		print_dir(runningProc->cwd);
	else
	{
		/* Not absolute pathname */
		if (pathName[0] != '/')
		{
			get_pwd_name(runningProc->cwd, fullPath);
			strcat(fullPath, pathName);
		}
		/* Absolute pathname */
		else
			strcpy(fullPath, pathName);
			
		iLoc = get_inode_number(fullPath);
		if (iLoc.inodeNum == 0)
			printf("Could not find \"%s\"\n", pathName);
		else
		{
			mip = get_inode(iLoc.deviceHandle, iLoc.inodeNum);
			if (S_ISDIR(mip->inode.i_mode))
				print_dir(mip);
			else
			{
				char name[EXT2_MAX_FILE_LENGTH];
				base_name(fullPath, name);
				print_file(mip, name);
			}
			put_inode(mip);
		}
	}
	
	printf("********************************************************\n\n");
	
	return 1;
}
